package com.csun.cmny.provider.controller.admin;

import com.csun.cmny.base.constant.GlobalConstant;
import com.csun.cmny.core.annotation.ValidateAnnotation;
import com.csun.cmny.core.support.BaseController;
import com.csun.cmny.provider.device.watch.entity.WatchConstant;
import com.csun.cmny.provider.model.dto.watch.WatchAlarmClockDto;
import com.csun.cmny.provider.model.dto.watch.WatchAlarmClockPageQuery;
import com.csun.cmny.provider.resolver.CmnyMessageSource;
import com.csun.cmny.provider.service.DmcWatchAlarmClockService;
import com.csun.cmny.provider.validator.DmcWatchAlarmClockAddValidator;
import com.csun.cmny.provider.validator.DmcWatchAlarmClockEditValidator;
import com.csun.cmny.util.CheckFileUtil;
import com.csun.cmny.util.FileTypeUtil;
import com.csun.cmny.util.wrapper.WrapMapper;
import com.csun.cmny.util.wrapper.Wrapper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Preconditions;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2019-01-25 14:52
 * @Description: the class dmc watch alarm clock controller
 */
@RestController
@RequestMapping(value = "/watch", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class DmcWatchAlarmClockController extends BaseController {

    @Resource
    private CmnyMessageSource cmnyMessageSource;

    @Resource
    private DmcWatchAlarmClockService dmcWatchAlarmClockService;

    /**
     * 查询孝心手环提醒列表
     */
    //@LogAnnotation(isSaveRequestData = true, isSaveResponseData = true)
    @RequestMapping(value = "/queryDmcWatchAlarmClockListWithPage", method = RequestMethod.POST)
    public Wrapper queryDmcWatchAlarmClockListWithPage(@RequestBody WatchAlarmClockPageQuery watchAlarmClockPageQuery) {

        PageInfo pageInfo = dmcWatchAlarmClockService.queryDmcWatchAlarmClockListWithPage(watchAlarmClockPageQuery);

       // return WrapMapper.ok(pageInfo);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),pageInfo);
    }

    /**
     * 添加孝心手环提醒
     */
    @ValidateAnnotation
    //@LogAnnotation(isSaveRequestData = true, isSaveResponseData = true)
    @RequestMapping(consumes = "multipart/form-data", value = "/addDmcWatchAlarmClock", method = RequestMethod.POST)
    public Wrapper addDmcWatchAlarmClock(@Validated(value = DmcWatchAlarmClockAddValidator.class)
                                                     WatchAlarmClockDto watchAlarmClockDto,
                                         BindingResult br, HttpServletRequest request) {

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> fileList = multipartRequest.getFiles("file");
        try {

            // 当闹钟类型大于2时校验
            if (watchAlarmClockDto.getClockType() > 2) {
                // 校验文件
                Preconditions.checkArgument(!fileList.isEmpty(),
                        cmnyMessageSource.getMessage("watch.alarm.clock.voice.data.null", null));
            }

            checkAlarmClockFile(watchAlarmClockDto, fileList);
        } catch (IOException e) {
            logger.error("上传语音文件失败={}", e.getMessage(), e);
        }

        Integer result = dmcWatchAlarmClockService.addDmcWatchAlarmClock(watchAlarmClockDto, getLoginAuthDto());

      //  return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),result);
    }

    /**
     * 修改孝心手环提醒
     */
    @ValidateAnnotation
    //@LogAnnotation(isSaveRequestData = true, isSaveResponseData = true)
    @RequestMapping(consumes = "multipart/form-data", value = "/editDmcWatchAlarmClock", method = RequestMethod.POST)
    public Wrapper editDmcWatchAlarmClock(@Validated(value = DmcWatchAlarmClockEditValidator.class)
                                                      WatchAlarmClockDto watchAlarmClockDto,
                                          BindingResult br, HttpServletRequest request) {

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> fileList = multipartRequest.getFiles("file");
        try {
            // 当闹钟类型大于2时校验
            if (watchAlarmClockDto.getClockType() > 2) {

                checkAlarmClockFile(watchAlarmClockDto, fileList);
            }
        } catch (IOException e) {
            logger.error("上传语音文件失败={}", e.getMessage(), e);
        }

        Integer result = dmcWatchAlarmClockService.editDmcWatchAlarmClock(watchAlarmClockDto, getLoginAuthDto());

      //  return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),result);
    }

    private void checkAlarmClockFile(WatchAlarmClockDto watchAlarmClockDto, List<MultipartFile> fileList)
            throws IOException {

        for (MultipartFile multipartFile : fileList) {

            Preconditions.checkArgument(multipartFile.getSize() <= GlobalConstant.BLOB_MAX_SIZE,
                    cmnyMessageSource.getMessage("watch.alarm.clock.voice.data.size", null));
            InputStream inputStream = multipartFile.getInputStream();

            String inputStreamFileType = FileTypeUtil.getType(inputStream);
            CheckFileUtil.checkFileType(CheckFileUtil.FileTypeEnum.AUDIO.getType(), inputStreamFileType);
            watchAlarmClockDto.setVoiceData(multipartFile.getBytes());
            watchAlarmClockDto.setIsNeed(WatchConstant.IS_NEED);

        }
    }

    /**
     * 删除孝心手环闹钟
     */
   // @LogAnnotation(isSaveRequestData = true, isSaveResponseData = true)
    @RequestMapping(value = "/deleteDmcWatchAlarmClockById/{id}", method = RequestMethod.POST)
    public Wrapper deleteDmcWatchAlarmClockById(@PathVariable Long id) {

        Integer result = dmcWatchAlarmClockService.deleteDmcWatchAlarmClockById(id);

       // return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),result);
    }


//    /**
//     * 下載孝心手环提醒语音文件
//     */
//    @LogAnnotation(isSaveRequestData = true, isSaveResponseData = true)
//    @RequestMapping(value = "/downloadDmcWatchAlarmClockVoiceDataById/{id}", method = RequestMethod.POST)
//    public Wrapper queryDmcWatchAlarmClockVoiceDataById(@PathVariable Long id,
//                                                     HttpServletResponse response) throws IOException {
//
//        // 1.校验 闹钟Id
//        Preconditions.checkArgument(id != null,
//                cmnyMessageSource.getMessage("watch.alarm.clock.id.null", null));
//        DmcWatchAlarmClock dmcWatchAlarmClockQuery = dmcWatchAlarmClockService.selectByKey(id);
//        if (PublicUtil.isEmpty(dmcWatchAlarmClockQuery)) {
//            throw new DmcBizException(ErrorCodeEnum.DMC100610019, id);
//        }
//
//        if (PublicUtil.isEmpty(dmcWatchAlarmClockQuery.getVoiceData())) {
//            throw new DmcBizException(ErrorCodeEnum.DMC100610020, id);
//        }
//
//        byte[] data = dmcWatchAlarmClockQuery.getVoiceData();
//        String fileName = dmcWatchAlarmClockQuery.getId().toString() + ".amr";
//        response.setHeader("content-disposition", "attachment;filename=" + fileName);
//        InputStream inStream = new ByteArrayInputStream(data);
//        OutputStream os = response.getOutputStream();
//
//        byte[] buff = new byte[1024];
//        int len = -1;
//        while ((len = inStream.read(buff)) > 0) {
//            os.write(buff, 0, len);
//        }
//        os.flush();
//        os.close();
//
//        inStream.close();
////        fileName = URLEncoder.encode(fileName, "UTF-8");
////        response.reset();
////        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
////        response.addHeader("Content-Length", "" + data.length);
////        response.setContentType("application/octet-stream;charset=UTF-8");
////        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
////        outputStream.write(data);
////        outputStream.flush();
////        outputStream.close();
//
//        return WrapMapper.ok();
//    }

}
